package com.ytrsoft.ws;

import com.ytrsoft.bean.Action;
import com.ytrsoft.bean.IOType;
import com.ytrsoft.bean.Message;
import com.ytrsoft.io.IOInputStream;
import com.ytrsoft.io.IOInputStreamListener;
import com.ytrsoft.io.IOOutputStream;
import com.ytrsoft.io.IOOutputStreamListener;
import com.ytrsoft.task.ActionFactory;
import com.ytrsoft.utils.MsgKit;


public class IdeaSocket extends BaseSocket implements IOInputStreamListener, IOOutputStreamListener {

    private IOInputStream stdIn;
    private IOOutputStream stdErr;
    private IOOutputStream stdOut;

    public ActionFactory<IdeaSocket> getFactory() {
        return new ActionFactory<>(this);
    }

    @Override
    protected void initialized() {
        stdIn = new IOInputStream();
        stdIn.setOnIOInputStreamListener(this);
        stdErr = new IOOutputStream(System.err);
        stdErr.setOnIOOutputStreamListener(this);
        stdOut = new IOOutputStream(System.out);
        stdOut.setOnIOOutputStreamListener(this);
        System.setIn(stdIn);
        System.setOut(stdOut);
        System.setErr(stdErr);
    }

    @Override
    public void input(Action action) {
        Message msg = MsgKit.create(action);
        postMessage(msg);
    }

    @Override
    public void out(IOType type, String body, boolean hasNewLine) {
        Message msg = MsgKit.create(type, body, hasNewLine);
        postMessage(msg);
    }

    public IOInputStream getStdIn() {
        return stdIn;
    }

    public IOOutputStream getStdOut() {
        return stdOut;
    }

    public IOOutputStream getStdErr() {
        return stdErr;
    }
}
